package com.chase.flashcleaner.utils

import java.io.File

const val K = 1024
const val M = 1024 * K
const val G = 1024 * M

data class FileDeleteInfo(val cnt: Int, val sizeKB: Double)

fun deleteDirectory(dir: File): FileDeleteInfo {
    if (dir.exists()) {
        var deletedCnt = 0
        var deleteSizeKB = 0.0
        dir.listFiles()?.forEach {
            if (it.isDirectory) {
                val info = deleteDirectory(it)
                if (info.cnt > 0) {
                    deletedCnt += info.cnt
                    deleteSizeKB += info.sizeKB
                }
            } else {
                val sizeKB = it.length() * 1.0 / K
                if (it.delete()) {
                    deletedCnt += 1
                    deleteSizeKB += sizeKB
                }
            }
        }
        dir.delete()
        return FileDeleteInfo(deletedCnt, deleteSizeKB)
    } else {
        // Dir does not exist
        return FileDeleteInfo(-1, 0.0)
    }
}

//fun deleteDirectory(dir: File): Int {
//    if (dir.exists()) {
//        var deletedCnt = 0
//        dir.listFiles()?.forEach {
//            if (it.isDirectory) {
//                val cnt = deleteDirectory(it)
//                if (cnt != -1) {
//                    deletedCnt += cnt
//                }
//            } else {
//                if (it.delete()) {
//                    deletedCnt += 1
//                }
//            }
//        }
//        dir.delete()
//        return deletedCnt
//    } else {
//        // Dir does not exist
//        return -1
//    }
//}